package com.example.springboot.ytest.ytest.date;

import java.time.Instant;
import java.time.LocalDateTime;
import java.time.OffsetDateTime;
import java.time.ZoneId;
import java.time.ZoneOffset;
import java.time.format.DateTimeFormatter;
import java.util.Date;

/**
 * DateTimeFormatter 替换 SimpleDateFormat
 * Intant 替换 Date
 * LocalDateTime 替换 Calendar
 * @author yeyi771
 */
public class DateTestJava8 {
    
    /**
     * http://blog.csdn.net/Hui_hai/article/details/78946004
     */
    static void t_1() {
        // date与instant的相互转化
        Instant now = Instant.now();
        Date date = Date.from(now);
        Instant instant = date.toInstant();
        // LocalDateTime代替Calendar
        ZoneId zoneId = ZoneId.systemDefault();
        LocalDateTime localDateTime = LocalDateTime.ofInstant(instant, zoneId);
        int year = localDateTime.getYear();
        int month = localDateTime.getMonthValue();
        int dayOfMonth = localDateTime.getDayOfMonth();
        int hour = localDateTime.getHour();
        int minute = localDateTime.getMinute();
        int second = localDateTime.getSecond();
        System.out.println("year: "+year);
        System.out.println("month: "+month);
        System.out.println("dayOfMonth: "+dayOfMonth);
        System.out.println("hour: "+hour);
        System.out.println("minute: "+minute);
        System.out.println("second: "+second);
        
        // DateTimeFormatter代替SimpleDateFormat
        DateTimeFormatter dateTimeFormatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
        // Date格式化成String
        String format = dateTimeFormatter.format(localDateTime);
        System.out.println("format: "+format);
        
        LocalDateTime parse = LocalDateTime.parse(format, dateTimeFormatter);
        ZoneOffset offset = OffsetDateTime.now().getOffset();
        Instant instant2 = parse.toInstant(offset);
        // 从String获得Date
        Date from = Date.from(instant2);
        System.out.println("from: "+from);
    }
    
    public static void main(String[] args) {
        t_1();
    }
}
